package com.qianfeng.pay;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.alipay.android.app.msp.demo.Keys;
import com.alipay.android.app.msp.demo.Result;
import com.alipay.android.app.msp.demo.Rsa;
import com.alipay.android.app.sdk.AliPay;
import com.qianfeng.pay.adapter.ProductListAdapter;
import com.qianfeng.pay.bean.ProductDetail;
import com.qianfeng.pay.util.ProductUtils;

import org.apache.http.client.utils.URLEncodedUtils;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    ArrayList<ProductDetail> mproductlist = new ArrayList<>();
    ProductListAdapter adapter;
    ListView productListView;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_OK:
                    super.handleMessage(msg);
                    Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        productListView = (ListView) findViewById(R.id.product_listview);

        ProductUtils.retrieveProductInfo(mproductlist);/////获取列表

        adapter = new ProductListAdapter(this, mproductlist);
        productListView.setOnItemClickListener(this);
        productListView.setAdapter(adapter);
        Button gopay = (Button) findViewById(R.id.gopay);
        gopay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(this, "前往支付", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Toast.makeText(this, "点击了某一项", Toast.LENGTH_SHORT).show();
        ProductDetail detail = mproductlist.get(position);
        gopay(detail);

    }

    private void gopay(ProductDetail detail) {
        ///1、将商户id, 收款账号，订单号，商品信息，回调路径等封装成商品订单信息
        String orderId = getOutTradeNo();
        String orderInfo = getOrderInfo(detail, orderId);/////拼接好的订单信息
        ///2、使用私钥对订单信息进行加密
        String strsign = Rsa.sign(orderInfo, Keys.PRIVATE);////加密后的订单信息
        strsign = URLEncoder.encode(strsign);///对加密后的订单信息进行编码

        ///3、将原始订单信息，加密后的订单信息，加密方式 封装成请求数据
        String signType = "sign_type=" + "\"" + "RSA" + "\"";///加密方式

        String info = orderInfo + "&sign=" + "\"" + strsign + "\"" + "&"  + signType;// 组装好的请求参数

        final String strSign = info;
        new Thread(new Runnable() {
            @Override
            public void run() {
                ///4、调用方法进行支付
                AliPay aliPay = new AliPay(MainActivity.this, handler);
                String result = aliPay.pay(strSign);
                Message msg = handler.obtainMessage();
                msg.what = RESULT_OK;
                msg.obj = result;
                handler.sendMessage(msg);

            }
        }).start();
    }

    String getOrderInfo(ProductDetail detail, String orderId) {
        /////公司要换成StringBuffer
        String strOrderInfo = "partner=" + "\"" + Keys.DEFAULT_PARTNER + "\"";
        strOrderInfo += "&";
        strOrderInfo += "seller=" + "\"" + Keys.DEFAULT_SELLER + "\"";
        strOrderInfo += "&";
        strOrderInfo += "out_trade_no=" + "\"" + orderId + "\"";
        strOrderInfo += "&";
        strOrderInfo += "subject=" + "\"" + detail.subject
                + "\"";
        strOrderInfo += "&";
        strOrderInfo += "body=" + "\"" + detail.body + "\"";
        strOrderInfo += "&";
        strOrderInfo += "total_fee=" + "\""
                + detail.price.replace("一口价:", "") + "\"";
        strOrderInfo += "&";
        strOrderInfo += "notify_url=" + "\""
                + "http://notify.java.jpxx.org/index.jsp" + "\"";

        return strOrderInfo;
    }

    public String getOutTradeNo() {
        //////这个是生产订单号的，要唯一
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String strKey = format.format(date);

        java.util.Random r = new java.util.Random();
        strKey = strKey + r.nextInt();
        strKey = strKey.substring(0, 15);
        return strKey;
    }
}
